"""
Schedule service for managing room schedules.
"""
from typing import List, Optional
from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from uuid import UUID
from app.models.schedule import Schedule
from app.models.room import Room
from app.schemas.schedule import ScheduleCreate, ScheduleUpdate


def get_schedule(db: Session, schedule_id: UUID) -> Optional[Schedule]:
    """Get a schedule by ID."""
    return db.query(Schedule).filter(Schedule.id == schedule_id).first()


def get_schedules(
    db: Session,
    room_id: Optional[UUID] = None,
    skip: int = 0,
    limit: int = 100
) -> List[Schedule]:
    """
    Get all schedules with optional room filter.
    
    Args:
        db: Database session
        room_id: Filter by room ID
        skip: Number of records to skip
        limit: Maximum number of records to return
        
    Returns:
        List of schedules
    """
    query = db.query(Schedule)
    
    if room_id:
        query = query.filter(Schedule.room_id == room_id)
    
    return query.order_by(Schedule.day_of_week).offset(skip).limit(limit).all()


def get_room_schedule(db: Session, room_id: UUID) -> List[Schedule]:
    """
    Get all schedules for a specific room.
    
    Args:
        db: Database session
        room_id: Room ID
        
    Returns:
        List of schedules for the room
    """
    return db.query(Schedule).filter(
        Schedule.room_id == room_id
    ).order_by(Schedule.day_of_week).all()


def create_schedule(db: Session, schedule: ScheduleCreate) -> Schedule:
    """
    Create a new schedule.
    
    Args:
        db: Database session
        schedule: Schedule creation schema
        
    Returns:
        Created schedule object
    """
    # Check if room exists
    room = db.query(Room).filter(Room.id == schedule.room_id).first()
    if not room:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Room not found"
        )
    
    # Check if schedule already exists for this room and day
    existing_schedule = db.query(Schedule).filter(
        Schedule.room_id == schedule.room_id,
        Schedule.day_of_week == schedule.day_of_week
    ).first()
    
    if existing_schedule:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Schedule already exists for this room on day {schedule.day_of_week}"
        )
    
    db_schedule = Schedule(**schedule.model_dump())
    db.add(db_schedule)
    db.commit()
    db.refresh(db_schedule)
    
    return db_schedule


def update_schedule(
    db: Session,
    schedule_id: UUID,
    schedule_update: ScheduleUpdate
) -> Schedule:
    """
    Update schedule information.
    
    Args:
        db: Database session
        schedule_id: Schedule ID
        schedule_update: Schedule update schema
        
    Returns:
        Updated schedule object
    """
    db_schedule = get_schedule(db, schedule_id)
    if not db_schedule:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Schedule not found"
        )
    
    update_data = schedule_update.model_dump(exclude_unset=True)
    
    for field, value in update_data.items():
        setattr(db_schedule, field, value)
    
    db.commit()
    db.refresh(db_schedule)
    
    return db_schedule


def delete_schedule(db: Session, schedule_id: UUID) -> bool:
    """
    Delete a schedule.
    
    Args:
        db: Database session
        schedule_id: Schedule ID
        
    Returns:
        True if deleted successfully
    """
    db_schedule = get_schedule(db, schedule_id)
    if not db_schedule:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Schedule not found"
        )
    
    db.delete(db_schedule)
    db.commit()
    
    return True


def create_default_schedule(db: Session, room_id: UUID) -> List[Schedule]:
    """
    Create default schedule (Mon-Fri 8:00-18:00) for a room.
    
    Args:
        db: Database session
        room_id: Room ID
        
    Returns:
        List of created schedules
    """
    from datetime import time
    
    # Check if room exists
    room = db.query(Room).filter(Room.id == room_id).first()
    if not room:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Room not found"
        )
    
    schedules = []
    # Monday to Friday (0-4)
    for day in range(5):
        schedule = Schedule(
            room_id=room_id,
            day_of_week=day,
            open_time=time(8, 0),
            close_time=time(18, 0),
            is_available=True
        )
        db.add(schedule)
        schedules.append(schedule)
    
    # Saturday and Sunday
    for day in range(5, 7):
        schedule = Schedule(
            room_id=room_id,
            day_of_week=day,
            open_time=time(0, 0),
            close_time=time(0, 0),
            is_available=False
        )
        db.add(schedule)
        schedules.append(schedule)
    
    db.commit()
    
    return schedules
